# coding=utf-8
# __author__ = "James Zhang"
# !/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import logging
import functools
import socket
import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.locale
import tornado.options
import tornado.web
from tornado.netutil import bind_sockets

from core.conf import settings
from core.utils.module_loading import import_module

settings.configure()

tornado.options.define('port', default=settings.DEFAULT_PORT, help='run at given port', type=int)
tornado.options.define('host', default=settings.DEFAULT_HOST, help='run at given host', type=basestring)

logging.getLogger('tornado.requests').setLevel(logging.WARNING)


HANDLERS = import_module(settings.HANDLERS)
urls = HANDLERS.url_pattens


class WebApplication(tornado.web.Application):
    def __init__(self):
        super(WebApplication, self).__init__(
            handlers=urls,
            ui_modules=import_module(settings.UI_MODULES),
            template_path=settings.TEMPLATE_DIR,
            static_path=settings.STATIC_DIR,
            debug=settings.DEBUG,
            cookie_secret=settings.COOKIE['secret'],
            xsrf_cookies=settings.COOKIE['csrf'],
            login_url=settings.LOGIN_URL,
        )
        # # tornado.locale.load_translations(setting.TRANSLATIONS_DIR, encoding=setting.ENCODING)
        # self.session_manager = session.CreateSessionManager(**setting.SESSION)
        # self.cache_manager = cache.CacheManager(**setting.CACHE)
        # self.db_parameter = setting.DATABASE
        # self.temp_dir = setting.TEMP_DIR
        self._cookie_name = settings.SESSION_COOKIE_NAME
        self._server_name = settings.HEADER_SERVER_NAME


if __name__ == "__main__":
    os.environ.setdefault("TORNADO_SETTINGS_MODULE", "core.settings")   # 设置环境变量
    tornado.options.parse_command_line()
    bind = functools.partial(bind_sockets, tornado.options.options.port, address=tornado.options.options.host)
    if settings.IPV4_ONLY:
        sockets = bind(family=socket.AF_INET)[0]
    else:
        sockets = bind()[0]
    application = WebApplication()
    http_server = tornado.httpserver.HTTPServer(application, xheaders=settings.XHEADERS)
    http_server.add_socket(sockets)
    tornado.ioloop.IOLoop.instance().start()


